package com.abcode.st.interceptor;

import com.abcode.st.common.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class RequestWrapperFilter extends OncePerRequestFilter {
    String streamType = "application/octet-stream";

    @Value("${biz.api.whitepath.url:/arrange}")
    private String whitepath;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestContentType = httpServletRequest.getContentType();
        String responseContentType = httpServletResponse.getContentType();
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(httpServletRequest);
        if (!inWhiteFilter(httpServletRequest, requestWrapper)){
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());
            httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
            Result apiResponse = Result.error("请求的路由暂时不开放");
            outputStream.write(apiResponse.toString().getBytes());
            return;
        }
       if(!streamType.equalsIgnoreCase(requestContentType) && !streamType.equalsIgnoreCase(responseContentType)){
           filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse);
       }else{
           filterChain.doFilter(httpServletRequest, httpServletResponse);
       }
    }
    /**
     * 过滤白名单
     * @param request
     * @param requestWrapper
     * @return
     */
    private boolean inWhiteFilter(HttpServletRequest request, ContentCachingRequestWrapper requestWrapper){
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        //TODO 这里要改 最好是有个前缀 这里可以根据自己的过滤逻辑来处理不同的路由，路由可以在配置文件中配置
        if(StringUtils.isEmpty(requestURI)){
            return false;
        }
        if(requestURI.contains(whitepath)){
            return false;
        }
        return true;
    }
}
